package cn.fl.capital.controller;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.capital.condition.CapAdvRuleInfoQueryCondition;
import cn.fl.capital.condition.CapPrjRuleRQueryCondition;
import cn.fl.capital.constant.CapitalConstant;
import cn.fl.capital.service.ICapAdvRuleInfoService;
import cn.fl.capital.vo.CapAdvRuleInfoVO;
import cn.fl.capital.vo.CapPrjRuleRVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.ref.fncprjbscinfo.service.IFncPrjBscInfoService;
import cn.fl.ref.fncprjbscinfo.transform.FncPrjBscInfoVOTransform;
import cn.fl.ref.fncprjbscinfo.vo.FncPrjBscInfoVO;
import cn.fl.system.constant.SysLogConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fl.ref.crbaseinfo.constant.CrBaseInfoConstant;
import fl.ref.fncprjbscinfo.condition.FncPrjBscInfoQueryCondition;
import fl.ref.fncprjbscinfo.constant.FncPrjBaseInfoConstant;
import fl.ref.fncprjbscinfo.dto.FncPrjBscInfoDTO;
import fl.ref.fribaseinfo.constant.FriBaseInfoConstant;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 垫款业务规则表 控制层
 */
@Controller
@RequestMapping("/capital/capAdvRuleInfo")
public class CapAdvRuleInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CapAdvRuleInfoController.class);

    /**
     * CapAdvRuleInfo 服务层BEAN
     */
    @Autowired
    private ICapAdvRuleInfoService capAdvRuleInfoService;

    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;

    @Autowired
    private IFncPrjBscInfoService fncPrjBscInfoService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toListPage", "加载CapAdvRuleInfo列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvRuleInfo/capAdvRuleInfoList");
        return mav;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载CapAdvRuleInfo Add页面.", CurrentThreadContext.getCurrentUserName());
        String ruleTypCd = request.getParameter("ruleTypCd");
        ModelAndView mav = null;
        if (StringUtils.isNotBlank(ruleTypCd) && "2".equals(ruleTypCd)) {
            mav = new ModelAndView("capital/capAdvRuleInfo/addAdvRuleInfoManual");
        } else {
            mav = new ModelAndView("capital/capAdvRuleInfo/capAdvRuleInfoModify");
        }
        this.prepare(request, mav);
        mav.addObject("capAdvRuleInfoVO", JSONObject.toJSON(new CapAdvRuleInfoVO()));
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toModifyPage", "加载CapAdvRuleInfo Modify页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvRuleInfo/capAdvRuleInfoModify");
        this.prepare(request, mav);

        String id = request.getParameter("id");
        CapAdvRuleInfoVO capAdvRuleInfoVO = this.capAdvRuleInfoService.selectById(Long.valueOf(id));
        if (null != capAdvRuleInfoVO) {
            if (null != capAdvRuleInfoVO.getAdvMinAmt()) {
                capAdvRuleInfoVO.setAdvMinAmtStr(DecimalUtils.convertFenToYuan(capAdvRuleInfoVO.getAdvMinAmt()));
            }
            if (null != capAdvRuleInfoVO.getAdvMaxAmt()) {
                capAdvRuleInfoVO.setAdvMaxAmtStr(DecimalUtils.convertFenToYuan(capAdvRuleInfoVO.getAdvMaxAmt()));
            }
        }
        mav.addObject("capAdvRuleInfoVO", JSONObject.toJSON(capAdvRuleInfoVO));
        CapPrjRuleRQueryCondition ruleRQueryCondition = new CapPrjRuleRQueryCondition();
        ruleRQueryCondition.setAdvRuleId(Long.valueOf(id));
        ruleRQueryCondition.setIsValid(1);
        List<CapPrjRuleRVO> capPrjRuleRVOList = this.capAdvRuleInfoService.selectCapPrjRuleRList(ruleRQueryCondition);
        StringBuilder sb = null;
        if (CollectionUtils.isNotEmpty(capPrjRuleRVOList)) {
            sb = new StringBuilder();
            for (int i = 0 ; i < capPrjRuleRVOList.size();i++) {
                sb.append(capPrjRuleRVOList.get(i).getFncPrjId());
                if(i != capPrjRuleRVOList.size() -1){
                    sb.append(",");
                }
            }
            mav.addObject("prjIdList",String.valueOf(sb));
        }
        return mav;
    }

    /**
     * 设置融资产品基本信息中关于字典项信息
     *
     * @param listVO
     */
    private void setListVOWithDicInfo(List<FncPrjBscInfoVO> listVO) {
        String sysCd = CapitalConstant.SYSCD;
        String orgCd = CapitalConstant.SYSORG;
        //CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()
        Map<String, String> countrylist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FncPrjBaseInfoConstant.FNC_PRJ_BSC_INFO_CTY);
        Map<String, String> bustypelist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FncPrjBaseInfoConstant.FNC_PRJ_BSC_INFO_BUS_TYPE);
        Map<String, String> firtypelist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FriBaseInfoConstant.FUND_RAS_INS_BASE_INFO_INS_TYPE_CD);
        Map<String, String> crsbjlist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, CrBaseInfoConstant.CR_BSC_INFO_CR_SBJ);
        Map<String, String> stcdlist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FncPrjBaseInfoConstant.FNC_PRJ_BSC_INFO_ST_CD);
        Map<String, String> transstlist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FncPrjBaseInfoConstant.FNC_PRJ_TRANS_ST_CD);
        Map<String, String> astIdlist = this.sysDictionaryApiService.searchGroupToMap(sysCd, orgCd, FncPrjBaseInfoConstant.FNC_PRJ_AST_ID);
        if (CollectionUtils.isEmpty(listVO)) {
            return;
        }
        for (FncPrjBscInfoVO vo : listVO) {
            //状态
            if (stcdlist.containsKey(vo.getFncprjstcd() + "")) {
                vo.setFncprjstNM(stcdlist.get(vo.getFncprjstcd() + ""));
            }
            //到账状态
            if (transstlist.containsKey(vo.getTransst() + "")) {
                vo.setTransstNM(transstlist.get(vo.getTransst() + ""));
            }
            if (countrylist.containsKey(vo.getCountry() + "")) {
                vo.setCountryNM(countrylist.get(vo.getCountry() + ""));
            }
            if (bustypelist.containsKey(vo.getBustype() + "")) {
                vo.setBustypeNM(bustypelist.get(vo.getBustype() + ""));
            }
            if (firtypelist.containsKey(vo.getInstypecd() + "")) {
                vo.setInstypeNM(firtypelist.get(vo.getInstypecd() + ""));

            }
            if (crsbjlist.containsKey(vo.getCrsbj() + "")) {
                vo.setCrsbjNM(crsbjlist.get(vo.getCrsbj() + ""));
            }
            if (vo.getFstpyamt() == null) {
                vo.setFstpyamt(0L);
            }
            if (vo.getFstpydepadd() != null) {
                vo.setFstpyamtall(vo.getFstpyamt() + Long.parseLong(vo.getFstpydepadd()));
            } else {
                vo.setFstpyamtall(vo.getFstpyamt());
            }
            //资产占用种类
            if (astIdlist.containsKey(vo.getAstId())) {
                vo.setAstNm(astIdlist.get(vo.getAstId()));
            }
        }
    }

    //加载数据字典数据、传值等 ？
    public void prepare(HttpServletRequest request, ModelAndView mav) {
        //规则状态 （"0": 未开启,"1":已开启）
        //List<KeyValueVO> advStatusKvList = this.sysDictionaryApiService.getKvList("", CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款日期类型（CAP0033 1：工作日 2：自然日(暂不考虑)）
        List<KeyValueVO> advDtKvList = this.sysDictionaryApiService.getKvList(CapitalConstant.CODE_CAP_ADV_DATE_TYP_CD, CapitalConstant.SYSCD, CapitalConstant.SYSORG);
        //垫款周期CAP0034 （1~5 ： 周一~周五）
        List<KeyValueVO> advPeriodKVList = this.sysDictionaryApiService.getKvList(CapitalConstant.CODE_CAP_ADV_PERIOD_TYP_CD, CapitalConstant.SYSCD, CapitalConstant.SYSORG);
        //CAP0029 垫款日期
        List<KeyValueVO> advTmKvList = this.sysDictionaryApiService.getKvList(CapitalConstant.CODE_CAP_ADV_TIME_TYP_CD, CapitalConstant.SYSCD, CapitalConstant.SYSORG);
        //垫款逾期天数CAP0030
        //List<KeyValueVO> advOverDueDaysKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款逾期期数CAP0031
        //List<KeyValueVO> advOverDuePayPdKvList = this.sysDictionaryApiService.getKvList("",CapitalConstant.SYSCD,CapitalConstant.SYSORG);
        //垫款方式CAP0032
        List<KeyValueVO> advWayKvList = this.sysDictionaryApiService.getKvList(CapitalConstant.CODE_CAP_ADV_WAY_TYP_CD, CapitalConstant.SYSCD, CapitalConstant.SYSORG);
        //垫款基数CAP0035
        List<KeyValueVO> advBaseCdKvList = this.sysDictionaryApiService.getKvList(CapitalConstant.CODE_CAP_ADV_BASE_TYP_CD, CapitalConstant.SYSCD, CapitalConstant.SYSORG);

        /*if(CollectionUtils.isNotEmpty(advStatusKvList)){
            mav.addObject("advStatusKvList", JSON.toJSONString(advStatusKvList));
        }*/

        if (CollectionUtils.isNotEmpty(advDtKvList)) {
            mav.addObject("advDtKvList", JSON.toJSONString(advDtKvList));
        }

        if (CollectionUtils.isNotEmpty(advPeriodKVList)) {
            mav.addObject("advPeriodKVList", JSON.toJSONString(advPeriodKVList));
        }

        if (CollectionUtils.isNotEmpty(advTmKvList)) {
            mav.addObject("advTmKvList", JSON.toJSONString(advTmKvList));
        }

        /*if(CollectionUtils.isNotEmpty(advOverDueDaysKvList)){
            mav.addObject("advOverDueDaysKvList", JSON.toJSONString(advOverDueDaysKvList));
        }

        if(CollectionUtils.isNotEmpty(advOverDuePayPdKvList)){
            mav.addObject("advOverDuePayPdKvList", JSON.toJSONString(advOverDuePayPdKvList));
        }*/

        if (CollectionUtils.isNotEmpty(advWayKvList)) {
            mav.addObject("advWayKvList", JSON.toJSONString(advWayKvList));
        }

        if (CollectionUtils.isNotEmpty(advBaseCdKvList)) {
            mav.addObject("advBaseCdKvList", JSON.toJSONString(advBaseCdKvList));
        }
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initCapAdvRuleInfoList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        CapAdvRuleInfoQueryCondition qc = new CapAdvRuleInfoQueryCondition();
        //TODO 设置查询条件？
        String ruleNm = request.getParameter("ruleNm");
        if (StringUtils.isNotEmpty(ruleNm)) {
            qc.setRuleNm(ruleNm);
        }
        String ruleTypCd = request.getParameter("ruleTypCd");
        if (StringUtils.isNotBlank(ruleTypCd)) {
            qc.setRuleTypCd(ruleTypCd);
        } else {
            qc.setRuleTypCd("1");
        }
        qc.setIsDel(0);
        page.setCondition(qc);

        BaseLogUtils.info(logger, "initCapAdvRuleInfoList", "初始化CapAdvRuleInfo列表页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        Pager pager = this.capAdvRuleInfoService.searchListPage(page);
        List<CapAdvRuleInfoVO> list = (List<CapAdvRuleInfoVO>) pager.getResultList();
        ListPageVO<CapAdvRuleInfoVO> listPage = new ListPageVO<CapAdvRuleInfoVO>(list, pager.getTotalCount());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeCapAdvRuleInfoByIds(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String ids = request.getParameter("ids");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(ids)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "removeCapAdvRuleInfoByIds", "删除CapAdvRuleInfo数据,主键参数为空!", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        List<Long> idsList = new ArrayList<Long>();
        JSONArray idsArray = JSONArray.fromObject(ids);
        for (Object object : idsArray) {
            idsList.add(Long.valueOf(object.toString()));
        }

        try {
            boolean success = this.capAdvRuleInfoService.removeByIds(idsList);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
                BaseLogUtils.info(logger, "removeCapAdvRuleInfoByIds", "删除CapAdvRuleInfo数据失败,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "removeCapAdvRuleInfoByIds", "删除CapAdvRuleInfo数据成功,ID:" + idsList.toString(), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "removeCapAdvRuleInfoByIds", "删除CapAdvRuleInfo数据失败,ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeCapAdvRuleInfoByIds", "删除CapAdvRuleInfo数据失败,系统错误.ID:" + idsList.toString() + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getCapAdvRuleInfoById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "getCapAdvRuleInfoById", "获取CapAdvRuleInfo数据,主键参数为空.", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            CapAdvRuleInfoVO vo = this.capAdvRuleInfoService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getCapAdvRuleInfoById", "获取CapAdvRuleInfo数据不存在,ID:" + id, CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getCapAdvRuleInfoById", "获取CapAdvRuleInfo数据成功,ID:" + id, CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.info(logger, "getCapAdvRuleInfoById", "获取CapAdvRuleInfo数据失败,ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getCapAdvRuleInfoById", "获取CapAdvRuleInfo数据失败,系统错误.ID:" + id + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addCapAdvRuleInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        CapAdvRuleInfoVO entity = null;//获取参数
        try {
            entity = this.getRequestParamForCapAdvRuleInfo(request);//获取参数
            Long id = this.capAdvRuleInfoService.add(entity);
            result.setData(id);
            BaseLogUtils.info(logger, "addCapAdvRuleInfo", "新增CapAdvRuleInfo数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addCapAdvRuleInfo", "新增CapAdvRuleInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addCapAdvRuleInfo", "新增CapAdvRuleInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增手动规则
     */
    @RequestMapping(value = "/addManualRuleInfo.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object addManualAdvRuleInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        CapAdvRuleInfoVO entity = null;//获取参数
        try {
            String idList = request.getParameter("ids");
            String dataList = request.getParameter("dataList");
            if (StringUtils.isBlank(idList) || StringUtils.isBlank(dataList)) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_PARAM_IS_BAD);
                BaseLogUtils.info(logger, "addManualRuleInfo", "项目主键ID不能为空！.数据为：" + idList, CurrentThreadContext.getCurrentUserName());
                return result;
            }
            String[] prjIdSplit = idList.split(",");
            List<Long> prjIdList = new ArrayList<>(prjIdSplit.length);
            for(int i=0;i<prjIdSplit.length;i++){
                prjIdList.add(Long.valueOf(prjIdSplit[i]));
            }
            entity = JSONObject.parseObject(dataList, CapAdvRuleInfoVO.class);
            entity.setIsValid(0);    //无效
            entity.setAdvTypCd("2"); //手动
            BaseLogUtils.info(logger, "addManualAdvRuleInfo", "CapAdvRuleInfoVO .DATA:" + JSON.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            Long id = this.capAdvRuleInfoService.addRuleInfoByManual(entity, prjIdList, CurrentThreadContext.getCurrentUserId());
            BaseLogUtils.info(logger, "addManualAdvRuleInfo", "新增CapAdvRuleInfo数据,ID ==>" + id, CurrentThreadContext.getCurrentUserName());
            if (null == id) {
                BaseLogUtils.info(logger, "addManualAdvRuleInfo", "新增CapAdvRuleInfo数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                BaseLogUtils.error(logger, "addManualAdvRuleInfo", "新增CapAdvRuleInfo数据成功,ID:" + id + ".DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_603, BaseExceptionConstant.BASE_EXCEPTION_CODE_603_NAME);
            }
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "addCapAdvRuleInfo", "新增CapAdvRuleInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "addCapAdvRuleInfo", "新增CapAdvRuleInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object modifyCapAdvRuleInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        CapAdvRuleInfoVO entity = null;
        try {
            entity = this.getRequestParamForCapAdvRuleInfo(request);
            if (entity.getId() == null) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
                BaseLogUtils.info(logger, "modifyCapAdvRuleInfo", "修改CapAdvRuleInfo信息,主键参数为空！.", CurrentThreadContext.getCurrentUserName());
                return result;
            }

            boolean success = this.capAdvRuleInfoService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
                BaseLogUtils.info(logger, "modifyCapAdvRuleInfo", "修改CapAdvRuleInfo数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
                return result;
            }
            BaseLogUtils.info(logger, "modifyCapAdvRuleInfo", "修改CapAdvRuleInfo数据成功.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.info(logger, "modifyCapAdvRuleInfo", "修改CapAdvRuleInfo数据失败.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR + ex.getMessage());
            BaseLogUtils.error(logger, "modifyCapAdvRuleInfo", "修改CapAdvRuleInfo数据失败,系统错误.DATA:" + JSONObject.toJSONString(entity) + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private CapAdvRuleInfoVO getRequestParamForCapAdvRuleInfo(HttpServletRequest request) throws BaseException {
        //获取参数
        String id = request.getParameter("id");//主键
        String ruleNm = request.getParameter("ruleNm");//垫款规则名称
        String advRate = request.getParameter("advRate");//垫款利率
        String ruleStsCd = request.getParameter("ruleStsCd");//规则状态  1.开启 0.关闭
        String dtTypCd = request.getParameter("dtTypCd");//垫款日期类型 CAP0033  1.工作日 2.自然日(暂时不考虑)
        String advCycCd = request.getParameter("advCycCd");//垫款周期CAP0034： 1-5 周一-周五
        String advTmCd = request.getParameter("advTmCd");//垫款时间 CAP0029
        String advMinAmt = request.getParameter("advMinAmt");//垫款租金最小值
        String advMaxAmt = request.getParameter("advMaxAmt");//垫款租金最大值
        String minOvdDay = request.getParameter("minOvdDay");//逾期起始天数
        String maxOvdDay = request.getParameter("maxOvdDay");//逾期截止天数
        String advPd = request.getParameter("advPd");//垫款期数
        String advBaseCd = request.getParameter("advBaseCd");//垫款基数（CAP0035）1.租金
        String advTypCd = request.getParameter("advTypCd");//垫款方式（垫款颗粒度）CAP0032  1.支付表 2.承租人3.汇总
        String advOvdDayCd = request.getParameter("advOvdDayCd");//垫款逾期天数（作废） CAP0030
        String advBkId = request.getParameter("advBkId");//垫款账户ID（作废）
        String advOvdPdCd = request.getParameter("advOvdPdCd");//垫款逾期期数（作废） CAP0031
        String ruleTypCd = request.getParameter("ruleTypCd"); //垫款类型

        //验证参数并赋值
        CapAdvRuleInfoVO entity = new CapAdvRuleInfoVO();
        entity.setRuleNm(ruleNm);//垫款规则名称
        if (StringUtils.isNotBlank(advRate)) {
            entity.setAdvRate(Double.valueOf(advRate));//垫款利率
        } else {
            entity.setAdvRate(null);//垫款利率
        }
        if (StringUtils.isNotBlank(ruleTypCd)) {
            entity.setRuleTypCd(ruleTypCd);
        }
        entity.setRuleStsCd(ruleStsCd);//规则状态  1.开启 0.关闭
        entity.setDtTypCd(dtTypCd);//垫款日期类型 CAP0033  1.工作日 2.自然日(暂时不考虑)
        entity.setAdvCycCd(advCycCd);//垫款周期CAP0034： 1-5 周一-周五
        entity.setAdvTmCd(advTmCd);//垫款时间 CAP0029
        if (StringUtils.isNotBlank(advMinAmt)) {
            entity.setAdvMinAmt(DecimalUtils.convertYuanToFen(Double.valueOf(advMinAmt)));//垫款租金最小值
        } else {
            entity.setAdvMinAmt(0L);
        }
        if (StringUtils.isNotBlank(advMaxAmt)) {
            entity.setAdvMaxAmt(DecimalUtils.convertYuanToFen(Double.valueOf(advMaxAmt)));//垫款租金最大值
        } else {
            entity.setAdvMaxAmt(0L);
        }
        if (StringUtils.isNotBlank(minOvdDay)) {
            entity.setMinOvdDay(Long.valueOf(minOvdDay));//逾期起始天数
        } else {
            entity.setMinOvdDay(0L);
        }
        if (StringUtils.isNotBlank(maxOvdDay)) {
            entity.setMaxOvdDay(Long.valueOf(maxOvdDay));//逾期截止天数
        } else {
            entity.setMaxOvdDay(0L);
        }
        if (StringUtils.isNotBlank(advPd)) {
            entity.setAdvPd(Long.valueOf(advPd));//垫款期数
        } else {
            entity.setAdvPd(null);
        }
        entity.setAdvBaseCd(advBaseCd);//垫款基数（CAP0035）1.租金
        entity.setAdvTypCd(advTypCd);//垫款方式（垫款颗粒度）CAP0032  1.支付表 2.承租人3.汇总
        entity.setAdvOvdDayCd(advOvdDayCd);//垫款逾期天数（作废） CAP0030
        if (StringUtils.isNotBlank(advBkId)) {
            entity.setAdvBkId(Long.valueOf(advBkId));//垫款账户ID（作废）
        } else {
            entity.setAdvBkId(null);
        }
        //entity.setAdvBkId(advBkId);//垫款账户ID（作废）
        entity.setAdvOvdPdCd(advOvdPdCd);//垫款逾期期数（作废） CAP0031

//		if (StringUtils.isBlank(name)) {
//            throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "名称不能为空.");
//      }
//      if (StringUtils.isNotBlank(num)) {
//          if (!StringUtils.isUnsignedNumeric(num)) {
//                throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "请填写正确的数字.");
//          }
//      }

        Date tm = new Date();
        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
            entity.setMdfTm(tm);
            entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        } else {
            entity.setCrtTm(tm);
            entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
            //entity.setCrtUsrOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前用户组织机构代码
            //entity.setOrgCd(CurrentThreadContext.getCurrentBuOrgCd());//事业部组织机构代码
        }

        return entity;
    }

    @RequestMapping(value = "/initFncPrjListPage.do",method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Object initFncPrjListPage(HttpServletRequest request, HttpServletResponse response){
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        FncPrjBscInfoQueryCondition qc = new FncPrjBscInfoQueryCondition();
        String isAdv = request.getParameter("isAdv");   //是否参与垫款
        String isSAdv = request.getParameter("isSAdv"); //是否开启垫款
        String prjIdList = request.getParameter("prjIdList");
        List<Long> prjIds = null ;
        if(StringUtils.isNotBlank(prjIdList)){
            String[] ids = prjIdList.split(",");
            prjIds = new ArrayList(ids.length);
            for(String id : ids){
                prjIds.add(Long.valueOf(id));
            }
        }
        BaseLogUtils.info(logger,"initFncPrjListPage","prjIds === "+prjIds+"=="+JSON.toJSONString(prjIds));
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
       /* if (StringUtils.isNotEmpty(isAdv)) {
            qc.setIsAdv(isAdv);
        } else {
            qc.setIsAdv("1");
        }
        if (StringUtils.isNotEmpty(isSAdv)) {
            qc.setIsSAdv(isSAdv);
        } else {
            qc.setIsSAdv("1");
        }
        if (CollectionUtils.isNotEmpty(prjIds)) {
            qc.setIdList(prjIds);
        }*/
        qc.setIsdel(0);
        qc.setIsvalid(1);
        //正常
        //qc.setFncprjstcd(7);
        page.setCondition(qc);
        page = this.fncPrjBscInfoService.searchListPage(page);
        List<FncPrjBscInfoVO> list = FncPrjBscInfoVOTransform.toVOList((List<FncPrjBscInfoDTO>) page.getResultList());
        ListPageVO<FncPrjBscInfoVO> listPage = new ListPageVO<FncPrjBscInfoVO>(list, page.getTotalCount());
        return listPage;
    }
    /**
     * 到选择页面
     */
    @RequestMapping(value = "/toChooseListPage.do", method = {RequestMethod.GET})
    public ModelAndView toChooseListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toChooseListPage", "加载CapAdvRuleInfo列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvRuleInfo/capAdvRuleInfoChoose");
        return mav;
    }

    /**
     * 到融资项目列表页面
     */
    @RequestMapping(value = "/toFnrPrjListPage.do", method = {RequestMethod.GET})
    public ModelAndView toFnrPrjListPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toFnrPrjListPage", "加载到融资项目列表页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("capital/capAdvRuleInfo/capFnrPrjInfoList");
        return mav;
    }
}

